﻿Imports System.Web.SessionState

Public Class Global_asax
    Inherits System.Web.HttpApplication
    Dim thisUser As New user
    Dim objDB As New DBConnect

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started


        Dim sql = "Select gameid, gg.goalid,goalname, isnull(goaldesc, ' ' ) goaldesc FROM game_goal gg left join goal on gg.goalid = goal.goalid"

        Dim ds As DataSet = objDB.getDataSet(sql)

        Dim t As DataTable = ds.Tables(0)
        t.Columns.Add("rank")

        Dim t2 As New DataTable
        t2.Columns.Add("gameid")
        t2.Columns.Add("nextgoal")

        t.DefaultView.Sort = "gameid, goalid"
        If t.DefaultView.Count > 0 Then

            Dim rank As Integer = -1
            Dim lastgameid As Integer = -1

            For i As Integer = 0 To t.DefaultView.Count - 1

                Dim currgameid As Integer = t.DefaultView(i).Item("gameid")
                If lastgameid <> currgameid Then
                    Dim r2 As DataRow = t2.NewRow
                    r2.Item("gameid") = currgameid
                    r2.Item("nextgoal") = 1
                    t2.Rows.Add(r2)
                    lastgameid = currgameid
                    rank = 0
                End If

                rank += 1
                t.DefaultView(i).Item("rank") = rank
            Next
        End If

        Application("gamegoaltable") = t
        Application("nextgoaltable") = t2

    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        Session("db") = objDB
        Session("user") = thisUser
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
    End Sub

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        Dim userID As Object = Session("user")

        Dim sqlString As String = "DELETE FROM Match_Player WHERE MatchID='" & Session("matchID") & "' AND ParticipantID='" & userID.participantID & "'"
        objDB.doUpdate(sqlString)

        Session("user") = ""
        Session("matchID") = ""
        Session("gameID") = ""

        objDB.resetConnection()
        objDB.closeConSql()
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application ends
    End Sub

End Class